<template>
  <ul class="list">
    <li class="item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        >{{item}}
        <!-- 三个vue滑动事件 -->
    </li>
  </ul>
</template>

<script>
export default {
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        // let in 遍历一个对象的key
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      timer: null
    }
  },
  update () {
    // 最初cities没有接到ajax数据时这个值是空的
    // 当它接收了值之后update这个钩子就会自动执行一下语句
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        // 利用定时器实现一个节流函数
        this.timer = setTimeout(() => {
          const startY = this.$refs['A'][0].offsetTop
          // 表示A字母距离绿色搜索栏的高度
          const touchY = e.touches[0].clientY - 79
          // e.touches[0].clientY 表示手指位置在屏幕上的Y坐标  79表示绿色搜索栏占的高度
          const index = Math.floor((touchY - startY) / 20)
          if (index >= 0 && index <= this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  },
  components: {

  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variables.styl'
.list
  display:flex
  flex-direction:column
  justify-content:center
  position:absolute
  top:1.58rem
  right:0
  bottom:0
  width:.4rem
  .item
    line-height:.44rem
    text-align:center
    color:$bgColor

</style>
